<template>
  <el-dialog
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    custom-class="dialogWrapper"
    :before-close="closeDialog">
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
      <el-form-item label="机构名称" prop="institutionName" required>
        <el-input v-model.trim="formData.institutionName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="机构简介" prop="institutionDetails">
        <el-input
          v-model.trim="formData.institutionDetails"
          type="textarea"
          class="textarea"
         auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="机构地址" prop="institutionAddress">
        <el-input v-model.trim="formData.institutionAddress" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="机构电话" prop="institutionPhone">
        <el-input v-model.trim="formData.institutionPhone" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="机构所属行业" prop="industry">
        <el-input v-model.trim="formData.industry" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="logo图片" prop="institutionLogoPic">
      	<div class="editImg" v-if="imgShow === 'edit'">
      		<img :src="imgSrc(formData.logoPicUrl)" />
      	</div>
        <el-upload
				  :action="baseUrl()"
				  list-type="picture-card"
				  :on-remove="handleRemove"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :auto-upload = "false"
				  :on-change="handleChangeImg"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
      </el-form-item>
      <el-form-item label="颜色" prop="institutionColour" required>
				  <input type="color" v-model.trim="formData.institutionColour"/>
      </el-form-item>
			<el-form-item label="是否允许积分兑换" prop="isIntegral" required>
        <el-select v-model.trim="formData.isIntegral">
          <el-option v-for="(item,index) in ['不允许','允许']" :value="String(index)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="1元兑换积分" v-if="formData.isIntegral ==='1'" prop="integralExchange"  required>
        <el-input v-model.trim="formData.integralExchange" auto-complete="off"></el-input>
      </el-form-item>
			<el-form-item label="商品折扣(百分比%)" prop="discount">
				<el-col :span="3">
        <el-input v-model.trim="formData.discount" auto-complete="off"></el-input>
				</el-col>%
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')" :disabled="Subabled">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { create, edit } from "@/services/institution";
import { getInsFromData} from "@/services/getFromData";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import editorImage from "@/components/Tinymce/components/editorImage";
var serialize = require('form-serialize');
var vailMobile = (rule, value, callback) => {
	var MobileRegex = /^1[34578]\d{9}$/;
	if (!MobileRegex.test(value)) {
	    callback(new Error('机构电话格式不正确！(仅支持手机号)'))
	    } else {
	        callback();
	    }
};
var vailNumber = (rule, value, callback) => {
	var NumberyRegex = /^[0-9]*$/;
	if (!NumberyRegex.test(value)) {
	    callback(new Error('格式不正确,只能输入数字'))
	    } else {
	        callback();
	    }
};
var vailDiscount = (rule, value, callback) => {
	var NumberyRegex = /^(?:[1-9]?\d|100)$/;
	if (!NumberyRegex.test(value)) {
	    callback(new Error('格式不正确,只能输入0-100以内的数'))
	    } else {
	        callback();
	    }
};
export default {
  name: "edit-role",
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }
    return {
      menus: [],
      list: [],
      file:{},
      formData: {
        institutionName: "",
        institutionDetails: "",
        institutionAddress: "",
        institutionPhone: "",
        industry: "",
        institutionColour: "#000000",
				integralExchange: "",
				discount:"100",
				isIntegral:""
			},
      imgShow:"",
      Subabled:false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      menuInfo: [],
      rules: {
        institutionName: [{ required: true, message: "请输入机构名称", trigger: "blur" },
        { min: 1, max: 50, message: '长度在 50个字符以内', trigger: 'blur' }],
        institutionDetails: [{ required: false, message: "请输入机构简介", trigger: "blur" },
        { min: 1, max: 200, message: '长度在 200个字符以内', trigger: 'blur' }],
        institutionAddress: [{ required: false, message: "请输入机构地址", trigger: "blur" },
        { min: 1, max: 100, message: '长度在 100个字符以内', trigger: 'blur' }],
        institutionPhone: [
    			{ required: true, message: '请输入机构电话', trigger: 'blur' },
   			  { validator: vailMobile, trigger: 'blur'}
   			],
        industry: [{ required: false, message: "请输入机构所属行业", trigger: "blur" },
        { min: 1, max: 10, message: '长度在 10个字符以内', trigger: 'blur' }],
        institutionColour: [{ required: true, message: "请输入颜色码", trigger: "blur" }],
        integralExchange: [{ required: true, message: "请输入1元兑换积分"},
        { min: 1, max: 12, message: '长度在 12个字符以内', trigger: 'blur' },
        { validator: vailNumber, trigger: 'blur'}
				],
				discount: [
    			{ required: false, message: '请输入折扣百分比', trigger: 'blur' },
   			  { validator: vailDiscount, trigger: 'blur'}
   			],
      }
    }
  },
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    validateMobile(rule, value, callback) {
		   var MobileRegex = /^1[0-9]{10}$/;
		     if (!MobileRegex.test(value)) {
		         callback(new Error('手机号码格式不正确！'))
		     } else {
		         callback();
		     }
		},
		imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
    closeDialog() {
      this.$emit("close");
    },
    baseUrl(){
    	return "api/console/institution/addInfo.do";
    },
		handleRemove(file, fileList) {
    	console.log(file, fileList);
 	 },
    handleChangeImg(file, fileList){
				this.imgShow = ""
	    	if(fileList.length > 1){
	    		this.$message.warning('当前限制选择 1个文件,多张图片覆盖第一张');
	    		var thisNode = document.getElementsByClassName("el-upload-list__item")[0];
	    		thisNode.parentNode.removeChild(thisNode);
	    	}
    	  var isJPG = ""
    	  if(file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'){
    		  isJPG = true
    	  }else{
    		  isJPG = false
    	  }
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG/png 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    submit(formName) {
    	this.Subabled = true;
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
							//把图片的信息和参数放进请求头里
							if(this.formData.isIntegral == "0"){
								this.formData.integralExchange = "";
							}
            	var sref = this;
            	//把图片的信息和参数放进请求头里
            	let code = await getInsFromData({
				        institutionName: this.formData.institutionName,
				        institutionDetails: this.formData.institutionDetails,
				        institutionAddress: this.formData.institutionAddress,
				        institutionPhone: this.formData.institutionPhone,
				        industry: this.formData.industry,
				        institutionColour: this.formData.institutionColour.substring(1,7),
								integralExchange: this.formData.integralExchange,
								discount: this.formData.discount,
								isIntegral:this.formData.isIntegral,
				      },"/ecshop/console/institution/addInfo.do").then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.Subabled = false;
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
									sref.Subabled = false;
								});
	          } 
            else {
            	if(this.formData.institutionColour.length == 7){
									this.formData.institutionColour = this.formData.institutionColour.substring(1,7)
							}
							if(this.formData.isIntegral == "0"){
								this.formData.integralExchange = "";
							}
              var sref = this;
            	//把图片的信息和参数放进请求头里
            	let code = await getInsFromData({
				    		id: this.formData.id,
				    		institutionNo: this.formData.institutionNo,
				        institutionName: this.formData.institutionName,
				        institutionDetails: this.formData.institutionDetails,
				        institutionAddress: this.formData.institutionAddress,
				        institutionPhone: this.formData.institutionPhone,
				        industry: this.formData.industry,
				        institutionColour: this.formData.institutionColour,
								integralExchange: this.formData.integralExchange,
								discount: this.formData.discount,
								isIntegral:this.formData.isIntegral,
				      },"/ecshop/console/institution/updateInfo.do").then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.Subabled = false;
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
									sref.Subabled = false;
								});
            }
            this.dialogFormVisible = false;
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    }
  },
  mounted() {},
  components: {
      'editorImage': editorImage
    }
};
</script>
<style>
.dialogWrapper {
  width: 540px;
}
.el-select {
  width: 100%;
}
.el-textarea__inner{
	height: 100px;
	resize:none;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
</style>
